import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:shop/common/common.dart';
import 'package:timercounter/timercounter.dart';

class SmsCounterView extends StatefulWidget {
  final String? phone;
  final bool isemail;
  const SmsCounterView({Key? key, this.phone, this.isemail = false}) : super(key: key);

  @override
  _SmsCounterViewState createState() => _SmsCounterViewState();
}

class _SmsCounterViewState extends State<SmsCounterView> {
  TimerCounter? _timer;
  int counter = 59;
  bool isstop = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _timer?.stop();
    super.dispose();
  }

  @override
  void didUpdateWidget(SmsCounterView oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  void _beginTimer() {
    if (mounted) {
      setState(() {
        isstop = false;
      });
    }
    _timer = TimerCounter.begin(
        duration: 59,
        callback: (timerCount) {
          if (mounted) {
            setState(() {
              counter = timerCount;
              if (timerCount <= 0) {
                counter = 59;
                isstop = true;
              }
            });
          }
        });
  }

  void _resend() async {
    String phone = widget.phone ?? "";
    if (widget.isemail && widget.phone == null) {
      EasyLoading.showError("请先绑定邮箱");
      return;
    }
    if (!widget.isemail && phone.length < 11) {
      EasyLoading.showError("请输入手机号码");
      return;
    }
    EasyLoading.show(status: "Loading...");
    await Future.delayed(const Duration(milliseconds: 500));
    EasyLoading.showToast("验证码已发送到${widget.phone}");
    EasyLoading.dismiss();
    _beginTimer();
  }

  @override
  Widget build(BuildContext context) {
    return isstop
        ? InkWell(
            onTap: _resend,
            child: Text(
              "获取验证码",
              style: AppFont.textStyle(16, color: AppColor.mainColor),
            ))
        : Text("重新获取（$counter秒）", style: AppFont.textStyle(16, color: AppColor.fontgrey));
  }
}
